import React, { useRef, useState } from 'react';
import {
  Card,
  makeStyles,
  Typography,
  CardActions,
  CardContent,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  CircularProgress,
  DialogActions,
} from '@material-ui/core';
import MarkdownIt from 'markdown-it';
import { useHistory } from 'react-router-dom';
import { deleteArticle } from '../../../api/actions/article';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
    margin: theme.spacing(2, 0, 2, 0),
  },
  previewContainer: {
    maxHeight: 300,
    overflow: 'hidden',
  },
}));
export default function ArticleList(props) {
  const { posts, type } = props;
  const classes = useStyles();
  const history = useHistory();

  const deletePidRef = useRef();
  const [openConfirm, setOpenConfirm] = useState(false);
  const [loadingDelete, setLoadingDelete] = useState(false);

  const handleLookArticle = (id) => {
    history.push(`/article/${id}`);
  };

  const handleWriteClick = (id) => {
    window.open(`/editor/${id}`, '_blank');
  };

  const handleDeleteClick = (id) => {
    deletePidRef.current = id;
    setOpenConfirm(true);
  };

  const handleDelete = async () => {
    setLoadingDelete(true);
    const res = await deleteArticle({ id: deletePidRef.current });
    if (res.code === 0) {
      setLoadingDelete(false);
      setOpenConfirm(false);
    }
  };

  const renderMarkdown = (markdown) => {
    const markdownIt = new MarkdownIt();
    return markdownIt.render(markdown);
  };

  const renderAction = (article) => {
    if (type === 'draft') {
      return (
        <>
          <Button variant="contained" color="primary" size="small" onClick={() => handleWriteClick(article._id)}>编写</Button>
          <Button size="small" color="secondary" onClick={() => handleDeleteClick(article._id)}>删除</Button>

        </>
      );
    } if (type === 'articles') {
      return (
        <>
          <Button variant="contained" color="primary" size="small" onClick={() => handleWriteClick(article._id)}>更新</Button>
          <Button size="small" color="secondary" onClick={() => handleDeleteClick(article._id)}>删除</Button>
        </>
      );
    } if (type === 'review') {
      return <Button variant="contained" color="primary" size="small" onClick={() => handleWriteClick(article._id)}>更新</Button>;
    } if (type === 'favorited') {
      return <Button variant="contained" color="primary" size="small" onClick={() => handleLookArticle(article._id)}>查看原文</Button>;
    }
    return null;
  };

  const handleCloseConfirm = () => {
    setOpenConfirm(false);
  };

  return (
    <>
      {
        Array.isArray(posts) && posts.map((item, index) => (
          <Card className={classes.root} key={index}>
            <CardContent>
              <Typography gutterBottom variant="h5" component="h2">
                {item.title || '无标题'}
              </Typography>
              <Typography
                dangerouslySetInnerHTML={{ __html: renderMarkdown(item.post) }}
                variant="body2"
                className={classes.previewContainer}
                color="textSecondary"
                component="p"
              />
            </CardContent>
            <CardActions>
              {renderAction(item)}
            </CardActions>
          </Card>
        ))
      }
      <Dialog
        open={openConfirm}
        onClose={handleCloseConfirm}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">确认删除吗?</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">
            删除将无法恢复，请谨慎删除。
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseConfirm} variant="contained" color="primary" size="small">
            取消
          </Button>
          <Button
            startIcon={loadingDelete && <CircularProgress size={20} color="inherit" />}
            disabled={loadingDelete}
            onClick={handleDelete}
            color="secondary"
            size="small"
          >
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
